package com.fzj.charging.order.rabbitmq;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fzj.charging.order.common.OrderStatusConstants;
import com.fzj.charging.order.config.RabbitMQConfiguration;
import com.fzj.charging.order.dao.mapper.OrderSuccessMapper;
import com.fzj.charging.order.pojo.po.OrderMQPO;
import com.fzj.charging.order.pojo.po.OrderSuccessPO;
import lombok.extern.slf4j.Slf4j;

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.core.Message;
import com.rabbitmq.client.Channel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;


@Component
@Slf4j
public class RabbitMQConsumer {
    @Autowired
    private OrderSuccessMapper orderSuccessMapper;

    //当消息到达指定的队列时，方法将被自动调用
    @RabbitListener(queues = RabbitMQConfiguration.DEAD_LETTER_QUEUE_NAME)
    public void receive(OrderMQPO orderMQPO, Message message, Channel channel){
        log.debug("消费到延迟消息，{}",orderMQPO);
        OrderSuccessPO orderSuccessPO = new OrderSuccessPO();

        orderSuccessPO.setBillStatus(OrderStatusConstants.ORDER_STATUS_EXCEPTION_END);
        UpdateWrapper<OrderSuccessPO> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("bill_id",orderMQPO.getOrderNo());
        updateWrapper.eq("bill_status",OrderStatusConstants.ORDER_STATUS_PROCESS);
        int updateRow = orderSuccessMapper.update(orderSuccessPO, updateWrapper);
        if(updateRow == 0){
            log.debug("订单正常结束");
        }else{
            log.debug("订单异常结束");
            log.debug("通知充电用户");
            log.debug("通知充维修人员");
        }

        try {
            //手动ack确认，告诉rabbitmq消费者已经收到消息并处理完毕，可以将消息删除
            // message.getMessageProperties().getDeliveryTag(): 这部分代码用于获取当前消息的“投递标签”（DeliveryTag）。每个从RabbitMQ队列中获取的消息都会分配一个唯一的投递标签，这个标签用于在确认消息时告诉RabbitMQ是哪条消息被确认了。getMessageProperties()方法返回消息的属性对象，其中包含了诸如投递标签、消息ID等信息。
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            log.debug("消费者手动确认消息收到");
        } catch (IOException e) {
            log.error("消费者手动确认消息出现异常");
        }

    }
}
